package logic

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"srv/model/mysql"
	"srv/pkg"
	"strconv"

	"srv/internal/svc"
	"srv/renrenzu"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderAddLogic {
	return &OrderAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderAddLogic) OrderAdd(in *renrenzu.OrderAddRequest) (*renrenzu.OrderAddResponse, error) {
	// todo: add your logic here and delete this line
	g := mysql.Goods{}
	err := g.Where(int(in.GoodsId))
	if err != nil {
		logx.Error("商品获取失败：", err)
		return nil, errors.New("商品获取失败")
	}
	if g.ID == 0 {
		logx.Error("商品不存在", err)
		return nil, errors.New("商品不存在")
	}
	if g.GoodsStock < int(in.Num) {
		logx.Error("库存不足", err)
		return nil, errors.New("库存不足")
	}
	sn := uuid.NewString()
	o := mysql.Orders{
		UserID:      int(in.UserId),
		GoodsID:     int(in.GoodsId),
		OrderTitle:  g.GoodsTitle,
		OrderCover:  g.GoodsCover,
		OrderAmount: g.GoodsPrice * float64(in.Num),
		OrderStock:  int(in.Num),
		OrderState:  g.GoodsState,
		OrderSn:     sn,
		Payment:     int(in.Payment),
	}
	err = o.Create()
	if err != nil {
		logx.Error("订单添加失败")
		return nil, errors.New("订单添加失败")
	}
	pay := pkg.NewALiPay()
	amount := strconv.FormatFloat(o.OrderAmount, 'f', 1, 64)
	alPay := pay.ALPay(o.OrderTitle, amount, o.OrderSn)
	return &renrenzu.OrderAddResponse{OrderId: int64(o.ID), Url: alPay}, nil
}
